<?php
App::uses('AppController', 'Controller');
/**
 * Categories Controller
 *
 * @property Category $Category
 * @property PaginatorComponent $Paginator
 */
class CategoriesController extends AppController {


/**
 * Components
 *
 * @var array
 */
	public $components = array('Paginator','Session');
        public $helpers = array('Form', 'Html', 'Js', 'Time','Session');
    
	var $name = 'Categories';
        public function beforeFilter() {

               $this->Auth->allow('display','cat','index','add', 'delete', 'edit','filter');
               if ($this->Auth->user('role')=='Admin'){
                   $this->layout='default';
               }
               else {
                     $this->layout='home';
               }
             
                Controller::loadModel('Menu');
                  $this->set('menus', $this->Menu->Find('all', array('conditions'=>array('Menu.position'=>'0'), 'order' => array('Menu.order' => 'asc'))));
                 $this->set('menusbottom', $this->Menu->Find('all', array('conditions'=>array('Menu.position'=>'1'), 'order' => array('Menu.order' => 'asc'))));
                  $this->set('menusleft', $this->Menu->Find('all', array('conditions'=>array('Menu.position'=>'2'), 'order' => array('Menu.order' => 'asc'))));
                  Controller::loadModel('Category');
                    Controller::loadModel('Location');
                   $nodelist = $this->Category->generateTreeList(null,null,null," - ");

           //			$this->set('parents',$this->Category->generatetreelist());
                   $this->set('parents',($nodelist));
                   $categories = $this->Category->find('list');
                   $locations = $this->Location->find('list');
                   $this->set(compact('locations'));
                   $this->set('params','');
                   
        Controller::loadModel('Paid_ads');
        $myDate = date("Y-m-d");
        // Left Ads
        $leftads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 2, 'Paid_ads.expired >=' => $myDate))));
        $this->set('leftbanners', $leftads);

        // Right Ads
        $rightads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 3, 'Paid_ads.expired >=' => $myDate))));
        $this->set('rightbanners', $rightads);

        // Top Header Ads
        $topheaderads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 4, 'Paid_ads.expired >=' => $myDate))));
        $this->set('topheaderads', $topheaderads);

        // Top Header Ads
        $bannerads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 5, 'Paid_ads.expired >=' => $myDate))));
        $this->set('bannerads', $bannerads);

        // Top Content Ads
        $topcontentads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 6, 'Paid_ads.expired >=' => $myDate))));
        $this->set('topcontentads', $topcontentads);

        // Top Content Ads
        $middlecontentads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 7, 'Paid_ads.expired >=' => $myDate))));
        $this->set('middlecontentads', $middlecontentads);

        // Top Content Ads
        $bottomcontentads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 8, 'Paid_ads.expired >=' => $myDate))));
        $this->set('bottomcontentads', $bottomcontentads);
        
        // Left Sidebar Ads
        $leftsidebarads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 9, 'Paid_ads.expired >=' => $myDate))));
        $this->set('leftsidebarads', $leftsidebarads);
        
        // Right Sidebar Ads
        $rightsidebarads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 10, 'Paid_ads.expired >=' => $myDate))));
        $this->set('rightsidebarads', $rightsidebarads);
            
             Controller::loadModel('Product');
        if($this->Session->check('order')){
           $data = $this->Session->read('order');
            $favoriteproduct = $this->Product->find('all', array('conditions' => array('Product.id' => $data)));
            $this->set('favoriteproducts', $favoriteproduct);
        }
           }
	function index() {
//		$this->Category->moveup(1,1);
//		$this->Category->reorder();
		if ($this->Auth->user('role') && $this->Auth->user('role')=='Admin'){
			$this->Category->recursive = 0;

			$this->set('categories', $this->Category->generateTreeList(null,null,null," - "));
  
		} else {
                return $this->redirect(array(
                                'controller' => 'posts',
                                'action' => 'index'));
            }
	}
	
	function mod() {
		$this->Category->id = 9;
		$this->Category->save(array('parent_id' => 1)); 
		$this->redirect(array('action' => 'index'));
	}

	function view($id = null) {
		if ($this->Auth->user('role') && $this->Auth->user('role')=='Admin'){
			if (!$id) {
				$this->Session->setFlash(__('Invalid category', true));
				$this->redirect(array('action' => 'index'));
			}
			$this->set('category', $this->Category->read(null, $id));
		} 
	}

	function add() {
		if ($this->Auth->user('role') && $this->Auth->user('role')=='Admin'){
			if (!empty($this->data)) {
				$this->Category->create();
                                $validate = true;
                                $allowedMime = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/jpg');

                                // Control Picture of Before
                                $requestimage = $this->request->data['Category']['image'];
                                if (!empty($requestimage['type']) && in_array($requestimage['type'], $allowedMime)) {
                                    $newfilename = date("YmdGis") . $requestimage['name'];
                                    if (!move_uploaded_file($requestimage['tmp_name'], WWW_ROOT . 'img' . DS . 'brand' . DS . $newfilename)) {
                                        $this->Category->invalidate('image', 'File was not uploaded, please try again.');
                                        $validate = false;
                                    } else {
                                        $this->request->data['Category']['image'] = $newfilename;
                                    }
                                } else {
                                    if (!empty($requestimage['tmp_name'])) {
                                        $this->Category->invalidate('image', 'Please supply a valid image (.jpg, .gif or .png)');
                                        $validate = false;
                                    } else {
                                        $this->request->data['Category']['image'] = NULL;
                                    }
                                }
				if ($validate && $this->Category->saveAssociated($this->request->data)) {
					$this->Session->setFlash(__('The category has been saved', true));
					$this->redirect(array('action' => 'index'));
				} else {
					$this->Session->setFlash(__('The category could not be saved. Please, try again.', true));
				}
			}
			$nodelist = $this->Category->generateTreeList(null,null,null," - ");
			$nodelist[0]='[No Parent]';
//			$this->set('parents',$this->Category->generatetreelist());
			$this->set('parents',($nodelist));
		} else {
                        return $this->redirect(array(
                                        'controller' => 'pages',
                                        'action' => 'index'));
                    }
	}

	function edit($id = null) {
            Controller::loadModel('Category');
		if ($this->Auth->user('role')=='Admin') {
			if (!$id && empty($this->data)) {
				$this->Session->setFlash(__('Invalid category', true));
				$this->redirect(array('action' => 'index'));
			}
			if (!empty($this->data)) {
                            $oldImage = $this->Category->find('all', array('conditions'=>array('Category.id'=>$id)));
                            // Control Picture of Before
                            $validate = true;
                            $allowedMime = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/jpg');

                            // Control Picture of Before
                            $requestimage = $this->request->data['Category']['image'];
                            if (!empty($requestimage['type']) && in_array($requestimage['type'], $allowedMime)) {
                                $newfilename = date("YmdGis") . $requestimage['name'];
                                if (!move_uploaded_file($requestimage['tmp_name'], WWW_ROOT . 'img' . DS . 'brand' . DS . $newfilename)) {
                                    $this->Category->invalidate('image', 'File was not uploaded, please try again.');
                                    $validate = false;
                                } else {
                                    $this->request->data['Category']['image'] = $newfilename;
                                    $imageade = new File(WWW_ROOT ."/img/brand/".$oldImage[0]['Category']['image']);
                                    $imageade->delete();
                                }
                            } else {
                                if (!empty($requestimage['tmp_name'])) {
                                    $this->Category->invalidate('image', 'Please supply a valid image (.jpg, .gif or .png)');
                                    $validate = false;
                                } else {
                                    $this->request->data['Category']['image'] = $oldImage[0]['Category']['image'];
                                }
                            }
                            if ($validate && $this->Category->saveAssociated($this->request->data)) {
                                    $this->Session->setFlash(__('The category has been saved', true));
                                    $this->redirect(array('action' => 'index'));
                            } else {
                                    $this->Session->setFlash(__('The category could not be saved. Please, try again.', true));
                            }
			}
			if (empty($this->data)) {
				$this->data = $this->Category->read(null, $id);
			}
                        $nodelist = $this->Category->generateTreeList(null,null,null," - ");
               
//			$this->set('parents',$this->Category->generatetreelist());
                        $this->set('parents',($nodelist));
                        $categories = $this->Product->Category->find('list');
		} else {
			//must be admin to edit locations
			$this->Session->setFlash(__('You do not have access to this.', true));
			$this->redirect(array('controller'=>'products','action' => 'index'));
		}//endif
	}
          function filter($id=null, $type=null, $location=null, $status=null, $price=null){
                parent::beforeFilter();
                 $this->layout = 'home';
//              echo $id.$type.$location.$status.$price;
//              die();
                Controller::loadModel('Product');
                Controller::loadModel('Category');
                Controller::loadModel('Paid_ads');
                $category = $this->Category->find('all', 
                    array('conditions' => array ('Category.parent_id' => $id))
                );
                 $title = $this->Category->find('first', 
                    array('conditions' => array ('Category.id' => $id))
                );
                $this->set('titles', $title);
                $leftcat = $this->Category->find('all', 
                    array('conditions' => array ('Category.parent_id' => $id))
                );
            $allbrands = $this->Product->find('all', array('conditions' => array('Category.parent_id' => $id)));
          //  $leftcat = $this->Product->find('all', array('conditions' => array('Category.parent_id' => $id)));
           
            // Promotion of product in each category
            $productPromotion =  $this->Product->Find('all', array('limit' => 10, 'conditions' => array ('AND' => array('Product.type' => 'promotion', 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                $this->set('productPromotion', $productPromotion);
            if(!empty($type) && empty($location) && empty($status) && empty($price)){
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.type' => $type, 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);
             
            }elseif(!empty($location) && empty($type) && empty($status) && empty($price)){
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.location_id' => $location, 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);

            }elseif(!empty($status) && empty($type) && empty($location) && empty($price)){
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.status' => $status, 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);

            }elseif(!empty($price) && empty($type) && empty($location) && empty($status)){
                $data=  explode('-', $price);
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.price >=' => $data[0], 'Product.price <=' => $data[1], 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);

            }elseif(!empty($price) && !empty($type) && empty($location) && empty($status)){
                $data=  explode('-', $price);
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.type' => $type, 'Product.price >=' => $data[0], 'Product.price <=' => $data[1], 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);

            }elseif(!empty($price) && !empty($type) && !empty($location) && empty($status)){
                $data=  explode('-', $price);
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.location_id' => $location, 'Product.type' => $type, 'Product.price >=' => $data[0], 'Product.price <=' => $data[1], 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);

            }elseif(!empty($price) && !empty($type) && !empty($location) && !empty($status)){
                $data=  explode('-', $price);
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.location_id' => $location, 'Product.type' => $type, 'Product.status' => $status, 'Product.price >=' => $data[0], 'Product.price <=' => $data[1], 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);

            }elseif(!empty($price) && empty($type) && !empty($location) && empty($status)){
                $data=  explode('-', $price);
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.location_id' => $location, 'Product.price >=' => $data[0], 'Product.price <=' => $data[1], 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);

            }elseif(!empty($price) && !empty($type) && empty($location) && !empty($status)){
                $data=  explode('-', $price);
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.type' => $type, 'Product.status' => $status, 'Product.price >=' => $data[0], 'Product.price <=' => $data[1], 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);

            }elseif(!empty($price) && empty($type) && !empty($location) && !empty($status)){
                $data=  explode('-', $price);
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.location_id' => $location, 'Product.status' => $status, 'Product.price >=' => $data[0], 'Product.price <=' => $data[1], 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);

            }elseif(!empty($price) && empty($type) && empty($location) && !empty($status)){
                $data=  explode('-', $price);
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.status' => $status, 'Product.price >=' => $data[0], 'Product.price <=' => $data[1], 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);

            }elseif(empty($price) && !empty($type) && !empty($location) && empty($status)){
                $data=  explode('-', $price);
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.location_id' => $location, 'Product.type' => $type, 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);

            }elseif(empty($price) && empty($type) && !empty($location) && !empty($status)){
                $data=  explode('-', $price);
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.location_id' => $location, 'Product.status' => $status, 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);

            }elseif(empty($price) && !empty($type) && empty($location) && !empty($status)){
                $data=  explode('-', $price);
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.type' => $type, 'Product.status' => $status, 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);

            }elseif(empty($price) && !empty($type) && !empty($location) && !empty($status)){
                $data=  explode('-', $price);
                 $product =  $this->Product->Find('all', array('limit' => 20, 'conditions' => array ('AND' => array('Product.type' => $type, 'Product.type' => $type, 'Product.location_id' => $location, 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
                 $this->set('products', $product);

            }else{
                 $product =  $this->Product->Find('all');
                  $this->set('products', $product);
            }
           
              $this->set('leftcats', $leftcat);
             $this->set('categories', $category);
            $this->set('allbrands', $allbrands);
            $this->set('params', $id);
            $this->set('select_type', $type);
            $this->set('select_location', $location);
            $this->set('select_status', $status);
             $this->set('select_price', $price);
         }
        function cat($id=null){
          parent::beforeFilter();
         $this->layout = 'home';
            Controller::loadModel('Product');
            Controller::loadModel('Category');
            Controller::loadModel('Paid_ads');
            Controller::loadModel('Comment');
            Controller::loadModel('Statistic');
                $category = $this->Category->find('all', 
                    array('conditions' => array ('Category.parent_id' => $id))
                );
                $title = $this->Category->find('first', 
                    array('conditions' => array ('Category.id' => $id))
                );
                $this->set('titles', $title);
                $leftcat = $this->Category->find('all', 
                    array('conditions' => array ('Category.parent_id' => $id))
                );
            $allbrands = $this->Product->find('all', array('conditions' => array('Category.parent_id' => $id)));
          //  $leftcat = $this->Product->find('all', array('conditions' => array('Category.parent_id' => $id)));
            $this->set('leftcats', $leftcat);
             $this->set('categories', $category);
            $this->set('allbrands', $allbrands);
            $this->set('params', $id);
        
            // Promotion of product in each category
            $productPromotion =  $this->Product->Find('all', array('limit' => 10, 'conditions' => array ('AND' => array('Product.type' => 'promotion', 'OR' => array('Category.parent_id' => $id, 'Category.id' => $id)))));
            $this->set('productPromotion', $productPromotion);
               
                
            // Query products                
            $this->Paginator->settings = array(
                'limit' => 10,
                'conditions' => array ('OR' => array('Category.parent_id' => $id, 'Category.id' => $id))
            );
            $this->Product->recursive = 1;
            $this->set('products', $this->Paginator->paginate('Product'));
            
            $countstatistic = $this->Statistic->find('all', array('conditions' => array('Statistic.date' => $date = date('Y/m/d'))));
            $this->set('counttoday', $countstatistic);
           
        }
        
                function delete($id = null) {
		if ($this->Auth->user('role') && $this->Auth->user('role')=='Admin'){
			if (!$id) {
				$this->Session->setFlash(__('Invalid id for category', true));
				$this->redirect(array('action'=>'index'));
			}
			if ($this->Category->delete($id)) {
				$this->Session->setFlash(__('Category deleted', true));
				$this->redirect(array('action'=>'index'));
			}
			$this->Session->setFlash(__('Category was not deleted', true));
			$this->redirect(array('action' => 'index'));
		} else {
                    return $this->redirect(array(
                                    'controller' => 'pages',
                                    'action' => 'index'));
                }
	}}
